package icu.yougan.trade.controller;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import icu.yougan.trade.entity.Address;
import icu.yougan.trade.entity.User;
import icu.yougan.trade.enums.ErrorMsg;
import icu.yougan.trade.service.AddressService;
import icu.yougan.trade.service.AuthenticationService;
import icu.yougan.trade.vo.R;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import java.net.InetSocketAddress;
import java.net.Proxy;


/**
 * @Author:油柑
 * @changeByLyh
 * @Date:2024/5/21 11:40
 * @Version:v1.0.0
 * @Description:添加地址 控制器
 **/
@CrossOrigin
@RestController
@RequestMapping("/address")
public class AddressController {
    @Resource
    private AddressService addressService;
    @Value("${baidu.baidu_AK}")
    private String Baidu_Ak;
    @Value("http://api.map.baidu.com/location/ip")
    private String BAIDU_MAP_API;
    @Resource
    private AuthenticationService authenticationService;
    /**
     * 通过id查询地址
     * @param id       地址id
     * @return 地址信息
     */
    @GetMapping("/info")
    public R getAddress(
            Authentication authentication,
            @RequestParam(value = "id", required = false) Long id
    ) {
        User user = authenticationService.getUserIdByAuthentication(authentication);
        if (null == id) {
            return R.success(addressService.getAddressByUser(Long.valueOf(user.getId())));
        } else {
            return R.success(addressService.getAddressById(id, Long.valueOf(user.getId())));
        }
    }

    /**
     * 通过百度API获取IP
     * @return
     */
    @GetMapping("/getAddressByBaidu")
    public R getAddressByBaidu()
    {
        // 1. 获取公网 IP
        String userIp = getPublicIp().trim();
        if (userIp == null || userIp.isEmpty()) {
            return R.fail(ErrorMsg.FALL_GET_IP);
        }
        // 2. 调用百度 API 获取位置
        String url = BAIDU_MAP_API+"?ak=" + Baidu_Ak + "&ip=" + userIp + "&coor=bd09ll";
        RestTemplate restTemplate = new RestTemplate();
        try {
            ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
            if (response.getStatusCode() == HttpStatus.OK) {
                return R.success(new ObjectMapper().readValue(response.getBody(), Object.class));
            } else {
                return R.fail(ErrorMsg.FALL_GET_BAIDU_API);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail(ErrorMsg.FALL_GET_IP);
        }
    }
    public String getPublicIp() {
        RestTemplate restTemplate = new RestTemplate();
        try {
            String url = "https://ip.3322.net";
            ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
            if (response.getStatusCode() == HttpStatus.OK) {
                return response.getBody();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取经纬度得到更准确的地址
     * @param lat
     * @param lng
     * @return
     */
    @GetMapping("getAddressDetails")
    public R getAddressDetails(@RequestParam("lat") double lat,
                               @RequestParam("lng") double lng)
    {
        System.out.println("lat="+lat);
        System.out.println("lat="+lng);
        String url=BAIDU_MAP_API+"?ak="+Baidu_Ak+"&output=json&location="+lat+","+lng;
        RestTemplate restTemplate=new RestTemplate();
        try
        {
            ResponseEntity<String>response=restTemplate.getForEntity(url,String.class);
            if(response.getStatusCode()==HttpStatus.OK)
            {
                ObjectMapper mapper=new ObjectMapper();
                Object dataObj=mapper.readValue(response.getBody(),Object.class);

                return R.success(ResponseEntity.ok(dataObj));
            }
            else
            {
                return R.fail(ErrorMsg.FALL_GET_BAIDU_API);
            }
        }catch (Exception e)
        {
            e.printStackTrace();
            return R.fail(ErrorMsg.FALL_GET_BAIDU_API);
        }
    }

    /**
     * 添加地址
     * @param authentication 认证对象容器
     * @param address  地址信息
     * @return 结果
     */
    @PostMapping("/add")
    public R addAddress(
            Authentication authentication,
            @RequestBody Address address
    ) {
        User user = authenticationService.getUserIdByAuthentication(authentication);
        address.setUserId(Long.valueOf(user.getId()));
        if (addressService.addAddress(address)) {
            return R.success(address);
        }
        return R.fail(ErrorMsg.SYSTEM_ERROR);
    }

    /**
     * 更新地址信息
     * @param address  地址信息
     * @param authentication 认证对象容器
     * @return 结果
     */
    @PostMapping("/update")
    public R updateAddress(
            Authentication authentication,
            @RequestBody Address address
    ) {
        User user = authenticationService.getUserIdByAuthentication(authentication);
        address.setUserId(Long.valueOf(user.getId()));
        if (addressService.updateAddress(address)) {
            return R.success();
        }
        return R.fail(ErrorMsg.SYSTEM_ERROR);
    }

    /**
     * 删除地址
     * @param address  地址信息
     * @param authentication 认证对象容器
     * @return 结果
     */
    @PostMapping("/delete")
    public R deleteAddress(
           Authentication authentication,
            @RequestBody Address address
    ) {
        User user = authenticationService.getUserIdByAuthentication(authentication);
        address.setUserId(Long.valueOf(user.getId()));
        if (addressService.deleteAddress(address)) {
            return R.success();
        }
        return R.fail(ErrorMsg.SYSTEM_ERROR);
    }
}
